/**
 * @Description OrderDataTimer.java
 * @author xu_cc [18724000100@163.com]
 * @date 创建时间：2018年1月8日 上午9:49:19
 */
package com.solution.admin.report.timer;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.solution.admin.order.entity.OrderEntity;
import com.solution.admin.order.service.OrderService;
import com.solution.admin.point.constants.PointConstants.TimerSwitch;
import com.solution.admin.report.entity.CustomerOrderDailyDataEntity;
import com.solution.admin.report.service.CustomerGrowthService;
import com.solution.admin.report.service.CustomerOrderDailyDataService;
import com.solution.common.config.PublicConfigUtil;
import com.solution.common.utils.DateUtils;

/**
 * 每日统计客户数据以及订单数据
 * 
 * @author xu_cc
 * @date 创建时间：2018年1月10日 下午3:25:03
 */
@Component
public class CustomerAndOrderDataByDateTimer implements InitializingBean {
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	@Autowired
	CustomerGrowthService customerGrowthService;

	@Autowired
	OrderService orderService;

	@Autowired
	CustomerOrderDailyDataService customerOrderDailyDataService;

	/** 每日数据统计 任务开关 key */
	static final String DAILY_DATA_SWITCH = "timer.daily.data.switch";

	/** 每日X时X分X秒开始执行 时间key */
	static final String DAILY_DATA_TIME = "timer.daily.data.time";

	@Override
	public void afterPropertiesSet() throws Exception {
		// 获取任务开关
		String timerSwitch = PublicConfigUtil.readConfig(DAILY_DATA_SWITCH);
		if (TimerSwitch.OFF.equals(timerSwitch)) {
			// 如果开关关闭，则不执行定时任务
			return;
		} else if (TimerSwitch.ON.equals(timerSwitch)) {
			// 一天的毫秒数
			long oneDay = 24 * 60 * 60 * 1000;
			String timer = PublicConfigUtil.readConfig(DAILY_DATA_TIME);// 每天几点执行
			// 计算初始延迟的毫秒数
			long initDelay = DateUtils.getTimeMillis(timer) - System.currentTimeMillis();
			/* 线程实现 */
			Runnable dailyDataRunnable = new Runnable() {
				@Override
				public void run() {
					logger.error("***************** 开始定时任务：每日数据统计 *******************");
					/* 主要是计算昨天的数据 */
					Calendar calendar = Calendar.getInstance();
					calendar.add(Calendar.DATE, -1);
					String today = DateUtils.formatDate(calendar.getTime(), "yyyy-MM-dd");
					String beginTime = today.concat(" 00:00:00");
					String endTime = today.concat(" 23:59:59");
					/**
					 * 1、获取客户总数
					 */
					Integer customerTotalCount = customerGrowthService.getCustomerTotal(endTime);
					/**
					 * 2、获取今日客户新增数量
					 */
					Integer customerGrowthCount = customerGrowthService.getCustomerCountByDate(beginTime, endTime);
					Map<String, Object> param = new HashMap<String, Object>();
					param.put("beginTime", beginTime);
					param.put("endTime", endTime);
					// 已完成
					// param.put("status", ORDER_STATUS.FINISHED.getCode());
					List<OrderEntity> orderList = orderService.listOrder(param);
					/**
					 * 3、获取今日订单金额
					 */
					BigDecimal orderTotalAmount = BigDecimal.ZERO;
					/**
					 * 4、获取今日订单数量
					 */
					Integer orderCount = 0;
					// 统计
					if (null != orderList && orderList.size() > 0) {
						// 订单数量
						orderCount = orderList.size();
						for (OrderEntity order : orderList) {
//							orderTotalAmount = orderTotalAmount.add(order.getOrderMoney());
							orderTotalAmount = orderTotalAmount.add(order.getRealPayMoney());
						}
					}
					CustomerOrderDailyDataEntity dailyData = new CustomerOrderDailyDataEntity();
					dailyData.setDate(calendar.getTime());
					dailyData.setCreater("system");
					dailyData.setCustomerTotalCount(customerTotalCount);
					dailyData.setCustomerGrowthCount(customerGrowthCount);
					dailyData.setOrderTotalAmount(orderTotalAmount);
					dailyData.setOrderCount(orderCount);
					customerOrderDailyDataService.insert(dailyData);
					logger.error("***************** 结束定时任务：每日数据统计 *******************");
				}
			};
			ScheduledExecutorService service = Executors.newSingleThreadScheduledExecutor();
			// 第二个参数为首次执行的延时时间，第三个参数为定时执行的间隔时间
			service.scheduleAtFixedRate(dailyDataRunnable, initDelay, oneDay, TimeUnit.MILLISECONDS);
		} else {
			logger.error("未知的定时任务开关值，请输入 on/off ");
		}
	}

//	/**
//	 * 两个日期之间的所有日期
//	 * 
//	 * @param begin
//	 * @param end
//	 * @return ArrayList<String>
//	 * @author xu_cc
//	 * @throws Exception
//	 *             exception
//	 * @Date 创建时间：2018年1月6日 下午5:53:18
//	 */
//	private ArrayList<String> getBetweenDate(String begin, String end) {
//		ArrayList<String> result = new ArrayList<String>();
//		try {
//			SimpleDateFormat paramFormat = new SimpleDateFormat("yyyy-MM-dd");// 格式化为年月
//			Calendar min = Calendar.getInstance();
//			Calendar max = Calendar.getInstance();
//			min.setTime(paramFormat.parse(begin));
//			min.set(min.get(Calendar.YEAR), min.get(Calendar.MONTH), min.get(Calendar.DATE));
//			max.setTime(paramFormat.parse(end));
//			max.set(max.get(Calendar.YEAR), max.get(Calendar.MONTH), max.get(Calendar.DATE) + 1);
//			Calendar curr = min;
//			while (curr.before(max)) {
//				result.add(paramFormat.format(curr.getTime()));
//				curr.add(Calendar.DATE, 1);
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
//		return result;
//	}
}
